package site.jlopen.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import site.jlopen.domain.datasource.event.KusciaDatasourceNodeEvent;
import site.jlopen.domain.node.event.KusciaNodeEvent;
import site.jlopen.entity.BaseResponse;
import site.jlopen.entity.KusciaApiInfo;
import site.jlopen.entity.req.NodeListReq;
import site.jlopen.entity.req.NodeReq;
import site.jlopen.kuscia.cons.DomainConstants;
import site.jlopen.kuscia.model.NodeVo;
import site.jlopen.kuscia.service.node.AbstractNodeManager;
import site.jlopen.mapper.datasource.KusciaDatasourceNodeMapper;
import site.jlopen.mapper.node.KusciaNodeMapper;
import site.jlopen.service.intf.node.NodeService;
import site.jlopen.utils.id.IdUtils;

@Service("NodeService")
public class NodeServiceImpl implements NodeService {
	private static Logger logger = LoggerFactory.getLogger(NodeServiceImpl.class);
	@Autowired
	private KusciaNodeMapper nodeMapper;
	@Autowired
    private AbstractNodeManager nodeManager;
	@Autowired
	private KusciaDatasourceNodeMapper dataSourceNodeMapper;
	
	@Override
	public BaseResponse<String> create(Long userId, NodeReq req) {
		KusciaNodeEvent event = nodeMapper.selectByInfo(new KusciaNodeEvent().setNodeUserId(userId).setNodeCode(req.getCode()));
		if(null != event) {
			return new BaseResponse<String>().error("该节点已存在");
		}
		event = new KusciaNodeEvent();
		event.setNodeId(IdUtils.SnowFlakeId())
		.setNodeUserId(userId)
		.setNodePlatform(req.getPlatform())
		.setNodeMode(req.getMode())
		.setNodeGroup(req.getGroup())
		.setNodeTitle(req.getTitle())
		.setNodeCode(req.getCode())
		.setNodeMaster(req.getMaster())
		.setNodeAuth(null)
		.setNodeGateway(req.getGateway())
		.setNodeGrpc(req.getGrpc())
		.setNodeHttp(req.getHttp())
		.setNodeNet(req.getNet())
		.setNodeProtocol(req.getProtocol())
		.setNodeToken(req.getToken())
		.setNodeCa(req.getCaFile())
		.setNodeCert(req.getCertFile())
		.setNodeKey(req.getKeyFile())
		.setNodeCreate(new Date())
		.setNodeEnable(1)
		;
		KusciaApiInfo apiInfo = new KusciaApiInfo(event.getNodeProtocol(), req.getGrpc()).ext(event.getNodeToken(), event.getNodeCert(), event.getNodeKey(), event.getNodeCa());
		NodeVo nodeVo = nodeManager.queryNode(apiInfo, req.getCode());
		if(null == nodeVo) {
			// 如果不存在节点，那么创建该节点
			nodeManager.createNode(apiInfo, req.getCode(), req.getMaster());
			nodeVo = nodeManager.queryNode(apiInfo, req.getCode());
		}
		if(null != nodeVo) {
			event.setNodeEnable(0);
			event.setNodeDeployToken(nodeVo.getToken());
		}
		int row = nodeMapper.insertSelective(event);
		if(row > 0) {
			return new BaseResponse<String>().success("创建成功，请稍后刷新状态");
		}
		return new BaseResponse<String>().error("创建失败");
	}

	@Override
	public BaseResponse<NodeVo> createLite(Long userId, NodeListReq req) {
		KusciaNodeEvent masterNode = nodeMapper.selectByKey(req.getMaster());
		if(null == masterNode) {
			return new BaseResponse<NodeVo>().error("主节点不存在");
		}
		KusciaNodeEvent lnode = nodeMapper.selectByInfo(new KusciaNodeEvent().setNodeGrpc(req.getGrpc()).setNodeCode(req.getCode()));
		if(null != lnode) {
			return new BaseResponse<NodeVo>().error("该节点已被其他账号注册");
		}
		KusciaApiInfo apiInfo = new KusciaApiInfo(masterNode.getNodeProtocol(), masterNode.getNodeGrpc())
				.ext(masterNode.getNodeToken(), masterNode.getNodeCert(), masterNode.getNodeKey(), masterNode.getNodeCa());
		NodeVo nodeVo = nodeManager.queryNode(apiInfo, req.getCode());
		if(null != nodeVo) {
			return new BaseResponse<NodeVo>().error("该节点已存在部署").setData(nodeVo);
		}
		boolean isC = nodeManager.createNode(apiInfo, req.getCode(), masterNode.getNodeCode());
		if(!isC) {
			return new BaseResponse<NodeVo>().error("节点注册失败，请查看系统日志");
		}
		nodeVo = nodeManager.queryNode(apiInfo, req.getCode());
		return new BaseResponse<NodeVo>().success("注册成功").setData(nodeVo);
	}

	@Override
	public BaseResponse<String> valid(Long userId, NodeReq nodeReq) {
		KusciaNodeEvent node = nodeMapper.selectByInfo(new KusciaNodeEvent().setNodeCode(nodeReq.getCode()).setNodeUserId(userId));
		if(null == node) {
			// 如果数据库不存在则使用传参
			node = new KusciaNodeEvent();
			node.setNodeProtocol(nodeReq.getProtocol())
			.setNodeGrpc(nodeReq.getGrpc())
			.setNodeToken(nodeReq.getToken())
			.setNodeCert(nodeReq.getCertFile())
			.setNodeKey(nodeReq.getKeyFile())
			.setNodeCa(nodeReq.getCaFile())
			.setNodeCode(nodeReq.getCode());
		}
		KusciaApiInfo apiInfo = new KusciaApiInfo(node.getNodeProtocol(), node.getNodeGrpc()).ext(node.getNodeToken(), node.getNodeCert(), node.getNodeKey(), node.getNodeCa());
		NodeVo nodeVo = nodeManager.queryNode(apiInfo, node.getNodeCode());
		if(null == nodeVo) {
			return new BaseResponse<String>().error("kuscia节点不存在");
		}
		return new BaseResponse<String>().success("测试成功");
	}

	@Override
	public List<KusciaNodeEvent> list(Long userId) {
		Map<String, Object> records = new HashMap<String, Object>();
		records.put("nodeUserId", userId);
		List<KusciaNodeEvent> list = nodeMapper.selectAllNotPage(records);
		/*KusciaApiInfo apiInfo = new KusciaApiInfo(event.getNodeProtocol(), "39.108.222.215:7003");
		for (KusciaNodeEvent node : list) {
			nodeManager.batchQueryNode(apiInfo, node.getNodeCode());
		}
		getNodeById("demand");*/
		return list;
	}

	@Override
	public List<KusciaNodeEvent> masterList(Long userId) {
		Map<String, Object> records = new HashMap<String, Object>();
		records.put("nodeUserId", userId);
		records.put("nodePlatform", "center");
		List<KusciaNodeEvent> list = nodeMapper.selectAllNotPage(records);
		return list;
	}

	@Override
	public List<KusciaDatasourceNodeEvent> listByDsId(Long datasourceId) {
		List<KusciaDatasourceNodeEvent> list = dataSourceNodeMapper.selectByDatasource(datasourceId);
		return list;
	}

	@Override
	public List<KusciaNodeEvent> listByNotDs(Long userId) {
		List<KusciaNodeEvent> list = nodeMapper.selectNotBindDatasource(userId);
		return list;
	}

	@Override
	public List<KusciaNodeEvent> listByRouteUser(Long userId, Long nodeId) {
		List<KusciaNodeEvent> list = nodeMapper.selectByRouteUser(userId, nodeId);
		return list;
	}

	@Override
	public void getNodeById(Long nodeId) {
		KusciaNodeEvent node = nodeMapper.selectByKey(nodeId);
		KusciaApiInfo apiInfo = new KusciaApiInfo(node.getNodeProtocol(), node.getNodeGrpc()).ext(node.getNodeToken(), node.getNodeCert(), node.getNodeKey(), node.getNodeCa());
		try {
			NodeVo nodeVo = nodeManager.queryNode(apiInfo, node.getNodeCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public BaseResponse<String> restatus(Long nodeId) {
		KusciaNodeEvent node = nodeMapper.selectByKey(nodeId);
		KusciaApiInfo apiInfo = new KusciaApiInfo(node.getNodeProtocol(), node.getNodeGrpc()).ext(node.getNodeToken(), node.getNodeCert(), node.getNodeKey(), node.getNodeCa());
		try {
			NodeVo nodeVo = nodeManager.queryNode(apiInfo, node.getNodeCode());
			if (nodeVo.getStatus().equals(DomainConstants.DomainEenableEnum.online.name())) {
				node.setNodeEnable(0);
			}else {
				node.setNodeEnable(1);
			}
			nodeMapper.updateSelective(node);
			return new BaseResponse<String>().success("同步成功");
		} catch (Exception e) {
			node.setNodeEnable(1);
			nodeMapper.updateSelective(node);
			return new BaseResponse<String>().error("同步失败:" + e.getMessage());
		}
	}
	

	@Override
	public BaseResponse<String> deleteNode(Long nodeId) {
		int row = nodeMapper.deleteByKey(nodeId);
		if(row > 0) {
			return new BaseResponse<String>().success("删除成功");
		}
		return new BaseResponse<String>().error("删除成功");
	}

	@Override
	public KusciaNodeEvent getNodeByCode(Long userId, String nodeCode) {
		if(null == userId || nodeCode == null) {
			return null;
		}
		KusciaNodeEvent event = nodeMapper.selectByInfo(new KusciaNodeEvent().setNodeUserId(userId).setNodeCode(nodeCode));
		return event;
	}

}
